package com.ddone.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.CannedAccessControlList;
import com.ddone.common.exception.BusinessException;
import com.ddone.common.result.ResponseEnum;
import com.ddone.oss.config.OssProperties;
import com.ddone.oss.service.FileService;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author ddone
 * @date 2024/4/16-09:51
 */
@Service
public class FileServiceImpl implements FileService {

    @Resource
    private OSS ossClient;

    @Override
    public String upload(InputStream inputStream, String module, String filename) {
        // 判断存储桶是否存在, 不存在则获取
        if(!ossClient.doesBucketExist(OssProperties.BUCKET_NAME)){
            // 不存在 创建
            ossClient.createBucket(OssProperties.BUCKET_NAME);
            // 设置访问权限为公共读
            ossClient.setBucketAcl(OssProperties.BUCKET_NAME, CannedAccessControlList.PublicRead);
        }

        // 构建日期路径
        String folder = new DateTime().toString("yyyy/MM/dd");
        // 文件名
        String fileName = UUID.randomUUID().toString().replace("-","") + filename.substring(filename.lastIndexOf("."));
        // 文件根路径
        String key = module + "/" + folder + "/" + fileName;
        // String key = module + "/" + filename;
        // 文件上传至阿里云
        ossClient.putObject(OssProperties.BUCKET_NAME, key, inputStream);

        return "https://"+OssProperties.BUCKET_NAME+"."+OssProperties.ENDPOINT+"/"+key;
    }

    @Override
    public void remove(String url) {
        String host = "https://" + OssProperties.BUCKET_NAME + "." + OssProperties.ENDPOINT + "/";
        String objectName = url.substring(host.length());
        if(! ossClient.doesObjectExist(OssProperties.BUCKET_NAME,objectName)){
            throw new BusinessException(ResponseEnum.DATA_NOT_EXIST);
        }
        // 删除文件
        ossClient.deleteObject(OssProperties.BUCKET_NAME, objectName);
    }
}
